/**
 * 
 */
package com.estock.platform.http;

import java.util.Date;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;

import com.estock.common.model.BaseDownloadObject;
import com.estock.common.model.security.Stock;
import com.estock.common.model.security.enums.StockType;
import com.estock.common.util.CommonUtil;
import com.estock.platform.http.client.GetClientProxy;
import com.estock.platform.http.client.URLDownloadClient;
import com.estock.platform.http.consts.RequestConsts;
import com.estock.platform.http.request.StockClientRequest;
import com.estock.platform.http.request.StockClientRequest.YahooCsvRequestBuilder;
import com.estock.platform.http.response.BaseResponse;
import com.estock.platform.http.response.DownloadResponse;

/**
 * @author richard
 *
 */
public class YahooCsvConn extends AbstractConnection {
	
	private static Logger logger = Logger.getLogger(YahooCsvConn.class);
	private Stock stock;
	
	public BaseResponse download(Stock stock) throws Exception {
		this.stock = stock;
		try {
			DownloadResponse response = 
					getResponse(DownloadResponse.class);
    		
	    	// for testing
			if (CommonUtil.isUnitTest) {
				BaseDownloadObject yahooCsv = response.getDownloadObject();
		    	if (yahooCsv != null) {
		    		logger.info("file name: " + yahooCsv.getFilename());
		    	}
			}
			
			return response;
		} catch (Exception e) {
			throw new RuntimeException("can not get valid stock information.", e);
		}
	}
	
	@Override
	protected GetClientProxy createStockClientProxy() {
		return new GetClientProxy(new URLDownloadClient() {

			@Override
			protected String getDownloadDirectory() {
				return CommonUtil.getYahooCsvDataDir() + stock.getCode() + ".csv";
			}
		});
	}


	@Override
	public StockClientRequest buildStockClientRequest(Object... params)
			throws Exception {
		// use this url: "http://ichart.yahoo.com/table.csv?s=000625.sz&a=5&b=1&c=1970&d=09&e=01&f=2030&g=d&ignore=.csv"
		YahooCsvRequestBuilder requestBuilder = StockClientRequest
				.getYahooCsvRequestBuilder(RequestConsts.URI_YAHOO_CSV)
				.appendStockCodeAndType(stock.getCode(), stock.getType());
		
		if (stock.getLastTransDay() != null) {
			// why add 1? for example last trans day is 7/14, today is 7/16
			// so what we want is data from 7/15, not 7/14.
			requestBuilder.appendDateRange(DateUtils.addDays(stock.getLastTransDay(), 1));
		}
		
		return (StockClientRequest) requestBuilder.buildQueryMessage();
	}
	
	
	/**
	 * Test Method
	 * 
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		Stock stock = new Stock("000625", "", StockType.SZ.getType()) {
			private static final long serialVersionUID = 1L;
			public Date getLastTransDay() {
				return DateUtils.addDays(new Date(), -2);
			}
		};
		new YahooCsvConn().download(stock);
	}

}
